<?php

namespace App\Handlers;

use App\Models\User;
use Intervention\Image\Facades\Image;

class ImageUploadHandler
{
    protected $allowed_ext = ['jpg','png','gif','jpeg'];

    public function save($file,$folder,$model_id,$max_width=false) {

        //获取文件后缀
        $extension = strtolower($file->getClientOriginalExtension()) ?: 'png';

        //判断是不是图片
        if(!in_array($extension,$this->allowed_ext)){
            return false;
        }

        //文件夹
        $folder_name = "uploads/images/{$folder}/".date('Ym/d',time());

        //物理地址
        $upload_path = public_path().'/'.$folder_name;

        //获取唯一文件名
        $filename = md5($model_id.time()).'.'.$extension;

        //将图片从临时保存区移动到指定位置，并重新命名
        $file->move($upload_path,$filename);

        $this->deleteOldImage($model_id);

        //缩放图片
        if ($max_width && $extension != 'gif') {
            $this->reduceSize($upload_path."/{$filename}",$max_width);
        }


        return [
            'path'=> config('app.url')."/$folder_name/$filename"
        ];

    }


    public function reduceSize( $file_path ,$max_width) {
        $image = Image::make($file_path);
        $image->resize($max_width, null, function ($obj) {
            //等比例缩放
            $obj->aspectRatio();
            //防止放大
            $obj->upsize();
        });
        $image->save();
    }


    public function deleteOldImage($user_id) {
        $user = User::find($user_id);

        if ($user) {
            $user_avatar = $user->avatar;
            $pic_arr = explode("/",$user_avatar);
            $relative_path = implode("/", array_slice($pic_arr, 3));
            $absolute_path = public_path().'/'.$relative_path;
            @unlink($absolute_path);
        }
    }
}
